<template>
  <div class="check-task">
    <div>
      <van-field label="计划名称" v-model="data.CheckPlanName" required>
      </van-field>
      <van-field
        class="input_text"
        v-model="data.CheckTypeName"
        label="检查类型"
        placeholder="请选择"
        required
        readonly
        @click="checkTypeName()"
      >
        <template #right-icon><van-icon name="arrow" /></template>
      </van-field>
      <van-field
        v-if="data.CheckType == 'ZCLX0002'"
        class="input_text"
        v-model="data.ItemTypeName"
        label="专项类型"
        placeholder="请选择专项类型"
        required
        readonly
        @click="chooseItemTypes()"
      >
        <template #right-icon><van-icon name="arrow" /></template>
      </van-field>
      <!-- 检查要求 -->
      <div class="problem">
        <div>
          <van-field class="input_text" label="检查要求" input-align="right">
            <template #input>
              <div></div>
            </template>
          </van-field>
        </div>
        <van-field
          v-model="data.CheckRequirement"
          rows="3"
          autosize
          type="textarea"
          placeholder="请输入检查要求"
        />
      </div>

      <van-field
        class="input_text"
        v-model="data.CheckNames"
        label="检查人"
        placeholder="请选择"
        type="textarea"
        rows="1"
        :autosize="true"
        required
        readonly
        @click="userChooseDialogShow = true"
      >
        <template #right-icon><van-icon name="arrow" /></template>
      </van-field>
      <van-field
        class="input_text problem"
        label="检查表"
        :placeholder="
          TCodes.length ? '已选择' + TCodes.length + '个检查表' : '请选择检查表'
        "
        :border="false"
        readonly
        @click="dangerTemplateShow = true"
      >
        <template #right-icon><van-icon name="arrow" /></template>
      </van-field>
      <!-- 日期 Date-->
      <date-picker
        label="开始时间"
        required
        :date.sync="data.StartDate"
      ></date-picker>
      <date-picker
        label="结束时间"
        required
        :date.sync="data.EndDate"
      ></date-picker>
      <van-field
        class="input_text"
        v-model="data.CheckFrequencyName"
        label="计划重复"
        required
        readonly
        @click="_chooseTask()"
      >
        <template #right-icon><van-icon name="arrow" /></template>
      </van-field>
      <van-field
        class="input_text"
        :value="data.Advance + '天'"
        label="提前生成"
        readonly
        @click="openAdvance"
      >
        <template #right-icon><van-icon name="arrow" /></template>
      </van-field>

      <!-- 单选框 -->
      <van-field class="input_text" name="radio" label="包含周末" required>
        <template #input>
          <van-radio-group
            v-model="data.IncludingWeekend"
            direction="horizontal"
          >
            <van-radio
              v-for="(item, index) in data.IncludingWeekends"
              :key="index"
              :name="item.ID"
              style="margin: 0 10px 10px 0"
              >{{ item.Name }}</van-radio
            >
          </van-radio-group>
        </template>
      </van-field>

      <van-field
        class="input_text"
        name="radio"
        label="检查模式"
        v-if="data.CheckNames && data.CheckNames.split(',').length > 1"
        required
      >
        <template #input>
          <van-radio-group
            v-model="data.JointInspection"
            direction="horizontal"
          >
            <van-radio
              v-for="(item, index) in data.JointInspections"
              :key="index"
              :name="item.ID"
              style="margin: 0 10px 10px 0"
              >{{ item.Name }}</van-radio
            >
          </van-radio-group>
        </template>
      </van-field>

      <van-field
        v-if="false"
        class="input_text mt-10"
        v-model="data.DCode"
        label="检查区域"
        :border="false"
        input-align="right"
      >
        <template #input>
          <!-- <span class="mr-20" style="color: green" @click="goInspectionWay()">巡检路线</span> -->
          <span style="color: green" @click="chooseDangerArea()">检查点</span>
        </template>
      </van-field>
      <div v-if="Details3.length" class="det_tab_item">
        <div class="operate_det">
          <div class="operate_list">
            <van-row class="operate_row_first">
              <van-col span="4">类别</van-col>
              <van-col offset="1" span="10">检查区域&检查表</van-col>
            </van-row>
            <van-checkbox-group>
              <van-row class="operate_row" v-for="(v, i) in Details3" :key="i">
                <van-col span="24">
                  <van-row>
                    <van-col span="5">
                      {{ v.CheckAreaTypeName || "风险位置" }}
                    </van-col>
                    <van-col span="17">
                      <div class="mb-5">检查区域：{{ v.CheckArea }}</div>
                      <div>检查表：{{ v.TNames || "无" }}</div>
                    </van-col>
                    <van-col span="2">
                      <van-checkbox :name="v" ref="checkboxes" />
                    </van-col>
                  </van-row>
                  <van-divider />
                  <van-row>
                    <van-col offset="6" span="18">
                      <van-row>
                        <van-col span="9">
                          <div @click="lookMyCheckListSet(v, i)">
                            <img
                              class="operation-imgs"
                              src="@/assets/Images/AppIcon/icon_list_verify.png"
                            />设置检查表
                          </div>
                        </van-col>
                        <van-col span="5">
                          <div @click="up(i)">
                            <img
                              class="operation-imgs"
                              src="@/assets/Images/AppIcon/icon_list_up.png"
                            />上移
                          </div>
                        </van-col>
                        <van-col span="5">
                          <div @click="down(i)">
                            <img
                              class="operation-imgs"
                              src="@/assets/Images/AppIcon/icon_list_down.png"
                            />下移
                          </div>
                        </van-col>
                        <van-col span="5">
                          <div @click="del(i)">
                            <img
                              class="operation-imgs"
                              src="@/assets/Images/AppIcon/icon_list_delete.png"
                            />删除
                          </div>
                        </van-col>
                      </van-row>
                    </van-col>
                  </van-row>
                </van-col>
              </van-row>
            </van-checkbox-group>
          </div>
        </div>
      </div>
      <div class="bottom-btns">
        <van-button class="submit-btn" type="primary" @click="save(true)">
          提交并立即发布
        </van-button>
        <van-button type="info" class="submit-btn" @click="save(false)">
          暂存稍后发布
        </van-button>
      </div>
    </div>
    <!--检查表选择-->
    <!-- <danger-template-choose-window
      :show.sync="dangerTemplateShow"
      @callback="dangerTemplateCallback"
    ></danger-template-choose-window> -->
   
    <danger-template-choose-dialog
      @callback="dangerTemplateCallback"
      @initList="_initListChcekTable"
      :params="params"
      :show.sync="dangerTemplateShow"
    >
    </danger-template-choose-dialog>
    
    <user-choose-dialog
      title="选择检查人"
      :show.sync="userChooseDialogShow"
      :tagData="userTagData"
      @callback="userChooseCallback"
      :isMulti="true"
    >
    </user-choose-dialog>
    <!--检查点-->
    <!--专项类型-->
    <van-popup
      v-model="ItemTypesShow"
      round
      position="bottom"
      :style="{ height: '80%' }"
    >
      <div class="popup-title">选择专项类型</div>
      <div class="popup-content">
        <ChooseItemTypes :data="data.ItemTypes" @cb="_chooseItemTypes" />
      </div>
    </van-popup>
    <CheckType :show.sync="show" :data="data" @cb="close" />
    <choose-task
      :show.sync="showChooseTask"
      :data="data"
      @close="closeChooseTask"
    />
    <change-day :show.sync="showAdvance" :data="data" @closeCb="closeAdvance" />
  </div>
</template>

<script>
import { getPatrolRouteDetail } from "@/api/sytech/sytechDangerPatrolRoute";
import {
  getDetail,
  AddCheckPlan,
  EditCheckPlan,
  checkPlanInitNewEntity,
} from "@/api/sytech/sytechDangerCheckPlan";
import ChooseItemTypes from "@/components/ChooseItemTypes/ChooseItemTypes.vue";
import UserChooseDialog from "@/views/components/user/userChooseDialog.vue";
import DatePicker from "../../../components/DatePicker.vue";
import ChooseTask from "../sytechDangerCheckPlan/ChooseTask";
import ChangeDay from "../sytechDangerCheckPlan/ChangeDay";
import store from "@/store/index";
import CheckType from "../sytechDangerCheckPlan/CheckType";
import DialogPageList from "@/components/DialogPageList.vue";
import DangerTemplateChooseDialog from "@/views/sytech/sytechDangerCheckTemplate/DangerTemplateChooseDialog.vue";

export default {
  components: {
    ChooseTask,
    ChangeDay,
    ChooseItemTypes,
    UserChooseDialog,
    DatePicker,
    CheckType,
    DialogPageList,
    DangerTemplateChooseDialog
  },
  data() {
    return {
      data: {},
      showCalendar: false,
      idx: "",
      show: false,
      showChooseTask: false,
      TCodes: [],
      Details3: [],
      showAdvance: false,
      ChooseDangerAreaShow: false,
      dangerTemplateShow: false,
      userChooseDialogShow: false,
      ItemTypesShow: false,
      filter: {
        id: this.$route.query.id,
        SourceID: 0,
      },
      params: [
        {
          title: "公共",
          Name: "Keywords",
          dataType: "CompanyList",
        },
      ],
      listUser: [],
      listCheckTable: [],
      userParams: [
        {
          Name: "ChnName",
          dataType: "List",
          accounted: true,
          userKind: 0,
        },
      ],
      chooseCheckTableUrl: "/SYQualityTemplate/GetPageData",
      chooseUserUrl: this.$constUrl.CHOOSE_USER,
      userTagData: [],
    };
  },
  created() {
    if (this.filter.id > 0) {
      store.commit("updateTitle", "编辑质量检查计划");
      this.getCheckPlan();
    } else {
      this.checkPlanInitNewEntity();
      store.commit("updateTitle", "创建质量检查计划");
    }
  },
  methods: {
    _initListUser(list) {
      this.listUser = list;
    },
    _initListChcekTable(list) {
      this.listCheckTable = list;
    },
    // 获取检查区域
    getPatrolRouteDetail(id) {
      getPatrolRouteDetail({ id }).then((res) => {
        res.data.forEach((item, index) => {
          this.Details3.forEach((item1, index1) => {
            if (item.CheckAreaCode == item1.CheckAreaCode) {
              this.Details3.splice(index1, 1);
            }
          });
        });
        this.Details3 = this.Details3.concat(res.data);
      });
    },
    // 修改天数
    openAdvance() {
      this.showAdvance = true;
    },
    closeAdvance(type) {
      if (type) {
        this.data.Advance = type;
      }
      this.showAdvance = false;
    },
    // 计划详情
    checkPlanInitNewEntity() {
      checkPlanInitNewEntity(this.filter).then((res) => {
        res.data.CheckTypes.push({ ID: 0, Name: "自定义" });
        this.data = res.data;
        this.userTagData=[];
        if (this.data.CheckCodes) {
          let checkUserNameArr = this.data.CheckCodes.split(",");
          for (var i = 0; i < checkUserNameArr.length; i++) {
            this.userTagData.push({
              code: checkUserNameArr[i],
            });
          }
        }
      });
    },

    // 计划详情
    getCheckPlan() {
      getDetail(this.filter).then((res) => {
        res.data.CheckTypes.push({ ID: 0, Name: "自定义" });
        this.data = res.data;
        this.TCodes = this.data.TCodes ? this.data.TCodes.split(",") : [];
        this.userTagData=[];
        if (this.data.CheckCodes) {
          let checkUserNameArr = this.data.CheckCodes.split(",");
          for (var i = 0; i < checkUserNameArr.length; i++) {
            this.userTagData.push({ code: checkUserNameArr[i] });
          }
        }
      });
    },

    // 选择检查类型
    checkTypeName() {
      this.show = true;
    },

    /* 上移 */
    up(index) {
      if (this.Details3.length > 1 && index !== 0) {
        this.Details3 = this.swapItems(this.Details3, index, index - 1);
      }
    },
    // 下移
    down(index) {
      if (this.Details3.length > 1 && index !== this.Details3.length - 1) {
        this.Details3 = this.swapItems(this.Details3, index, index + 1);
      }
    },
    swapItems(arr, index1, index2) {
      arr[index1] = arr.splice(index2, 1, arr[index1])[0];
      return arr;
    },
    // 删除
    del(index) {
      this.Details3.splice(index, 1);
    },
    // 选择专项类型
    chooseItemTypes() {
      this.ItemTypesShow = true;
    },
    _chooseItemTypes(ItemType) {
      if (ItemType) {
        this.data.ItemType = ItemType;
        this.data.ItemTypes.forEach((item) => {
          if (item.ID == this.data.ItemType) {
            this.data.ItemTypeName = item.Name;
          }
        });
      }
      this.ItemTypesShow = false;
    },
    // 选择路线
    goInspectionWay() {
      // this.$router.push('/SytechDanger/InspectionWay')
      this.$router.push({
        name: "InspectionWay",
        params: {
          path: "CheckTask",
        },
      });
    },
    dangerTemplateCallback(params) {
      this.dangerTemplateShow = false;
      this.data.TCodes = params.TCodes;
      this.data.TNames = params.TNames;
      this.TCodes = this.data.TCodes ? this.data.TCodes.split(",") : [];
    },
    // 设置检查表
    lookMyCheckListSet(item, idx) {
      this.$router.push({
        name: "MyCheckListSet",
        params: {
          path: "CheckTask",
          item: item,
          idx: idx,
        },
      });
    },
    // 选择检查点
    chooseDangerArea() {
      this.ChooseDangerAreaShow = true;
    },
    _chooseChooseDangerArea(Details) {
      this.Details3 = Details;
      this.ChooseDangerAreaShow = false;
    },
    userChooseCallback(userlist) {
      this.userTagData = userlist;
      if (userlist) {
        const code = userlist.map((item) => {
          return item.code;
        });
        const name = userlist.map((item) => {
          return item.name;
        });
        this.data.CheckNames = name.join(",");
        this.data.CheckCodes = code.join(",");
      }
      this.userChooseDialogShow = false;
    },
    // 选择计划重复
    _chooseTask() {
      this.showChooseTask = true;
    },
    closeChooseTask(type) {
      if (type) {
        this.data.CheckFrequencies.forEach((item) => {
          if (item.ID == type) {
            this.data.CheckFrequencyName = item.Name;
          }
        });
      }
      this.showChooseTask = false;
    },

    // 	检查类型
    close(type) {
      if (type) {
        if (type.indexOf("Custom") >= 0) {
          this.data.CheckTypeName = type.substring(7);
        } else {
          this.data.CheckTypes.forEach((item) => {
            if (item.ID == type) {
              this.data.CheckTypeName = item.Name;
            }
          });
        }
        this.data.CheckType = type;
      }

      this.show = false;
    },
    save(IsPublish) {
      if (!this.data.CheckPlanName) {
        return this.$toast("请填写计划名称");
      }
      if (!this.data.CheckType) {
        return this.$toast("请选择检查类型");
      }
      if (this.data.CheckType == "ZCLX0002") {
        if (!this.data.ItemType) {
          return this.$toast("请选择专项类型");
        }
      }
      if (!this.data.CheckNames) {
        return this.$toast("请选择检查人");
      }
      if (!this.data.IncludingWeekend) {
        return this.$toast("是否包含周末");
      }
      this.loading = true;
      let param = {
        ID: this.data.ID,
        SourceID: 0,
        IsPublish: IsPublish,
        CheckPlanName: this.data.CheckPlanName,
        CheckType: this.data.CheckType,
        ItemType: this.data.ItemType,
        CheckArea: this.data.CheckArea,
        CheckRequirement: this.data.CheckRequirement,
        TCodes: this.data.TCodes,
        TNames: this.data.TNames,
        CheckCodes: this.data.CheckCodes,
        CheckNames: this.data.CheckNames,
        StartDate: this.data.StartDate,
        EndDate: this.data.EndDate,
        CheckFrequency: this.data.CheckFrequency,
        Advance: this.data.Advance,
        AdvanceFrequency: this.data.AdvanceFrequency,
        IncludingWeekend: this.data.IncludingWeekend,
        JointInspection: this.data.JointInspection,
      };
      if (this.data.ItemType) {
        param.ItemType = this.data.ItemType;
      }
      if (this.Details3.length) {
        param.Details3 = this.Details3;
      }
      if (this.data.ID) {
        EditCheckPlan(param, IsPublish)
          .then((res) => {
            this.$toast("保存成功");
            this.loading = false;
            setTimeout(() => {
              this.$router.goRefresh();
            }, 500);
          })
          .catch((err) => {
            console.log("err", err);
          });
      } else {
        AddCheckPlan(param, IsPublish)
          .then((res) => {
            this.$toast("保存成功");
            this.loading = false;
            setTimeout(() => {
              this.$router.goRefresh();
            }, 500);
          })
          .catch((err) => {
            console.log("err", err);
          });
      }
    },
  },
};
</script>

<style lang="less" scoped>
.check-task {
  background-color: #e8f1f8;
  padding-bottom: 20px;
}
.problem {
  margin-bottom: 10px;
}
.bottom-btns {
  margin-top: 10px;
  padding: 0 10px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  .submit-btn {
    width: 48%;
    height: 35px;
    font-size: 14px;
  }
}

.det_tab_item {
  padding: 10px 0;
  background-color: #fff;
  border-radius: 5px;
  margin-bottom: 10px;

  .det_tab_item_text {
    padding: 0 10px;
  }
}
.operate_det {
  background-color: #fff;
  padding: 10px;
  .operate_list {
    font-size: 12px;
    border: 1px solid #e8f1f8;
    .operate_row_first {
      padding: 10px;
      background-color: #e8f1f8;
      border-bottom: 1px solid #e8f1f8;
      margin-bottom: 10px;
    }
    .operate_row {
      padding: 10px;
      border-bottom: 1px solid #e8f1f8;
      /*margin-bottom: 10px;*/
    }
  }
}
.operation-imgs {
  width: 15px;
  height: 15px;
  vertical-align: middle;
  margin-right: 5px;
}

.risk_item_radio {
  width: 100%;
  background-color: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  // border-bottom: 1px solid #e8f1f8;
}
</style>
